package com.learn.command.observable;

import com.learn.service.TestService;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixObservableCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import rx.Observable;
import rx.Subscriber;

/**
 * 使用HystrixObservableCommand时，默认会使用信号量隔离
 * 甚至连线程池都不能控制了
 *
 *
 */
@Component
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class HelloWorldSemaphoreIsolationCommand extends HystrixObservableCommand<String> {

    @Autowired
    private TestService testService;


    public HelloWorldSemaphoreIsolationCommand() {
        super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"));
    }



    @Override
    protected Observable<String> construct() {
        return Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> observer) {
                try {
                    if (!observer.isUnsubscribed()) {
                        // a real example would do work like a network call here
                        String s = testService.getResult();
                        observer.onNext(s);
                        observer.onCompleted();
                    }
                } catch (Exception e) {
                    observer.onError(e);
                }
            }
        } );
    }
}
